/* eslint-disable */
import axios from 'axios'
import store from '@/store'
import router from '../router'
const request = axios.create({
  baseURL: 'http://edufront.lagou.com'
})
// 设置请求拦截器健全请求，增加token
request.interceptors.request.use(config => {
  const { user } = store.state
  if (user && user.access_token) {
    config.headers.Authorization = user.access_token
  }
  return config
})
let isRefreshing = false
let callbacks = []
// 设置响应拦截器，处理token过期

request.interceptors.response.use(response => {
  return response
}, async error => {
  if (error.response) {
    if (error.response.status === 401) {
      // 判断是否有登录用户信息
      if (!store.state.user) {
        router.push({ name: 'Login', query: { directe: router.currentRoute.fullPath } })
        return Promise.reject(error)
      }
      if (isRefreshing) {
        // 如果正在刷新token,将这些请求先保存起来
        return callbacks.push(()=> {
          request(error.config)
        })
      }
      isRefreshing = true
      // 刷新token
      const { data }  = await request({ method: 'POST', url: '/front/user/refresh_token', data: new window.URLSearchParams({ refreshtoken: store.state.user.refresh_token }).toString() })
      if (data.state !== 1) {
        // 刷新token失败，情况用户登录信息，跳转到login界面
        store.commit('setUser', null)
        router.push({ name: 'Login', query: { directe: router.currentRoute.fullPath } })
        return Promise.reject(error)
      }
      // 刷新token成功，保存用户信息，重发失败的请求
      store.commit('setUser', data.content)
      callbacks.forEach(callback => callback())
      callbacks = []
      isRefreshing = false
      // 再把触发刷新token的请求重新发送
      return request(error.config)
    }
  }
  // console.log('没有返回信息')
  return Promise.reject(error)
})

export default request
